<?php
namespace haibao\www\business;

use \haibao\www\model\filter\FeaturePublish as FeaturePublishFilter;
use \haibao\www\model\data\FeaturePublish as FeaturePublishModel;
use \haibao\www\data\FeaturePublish as FeaturePublishData;
use \haibao\frame\data\query\Condition;
use \haibao\www\Config;
use \haibao\www\web\view\utility\File as FileUtility;
use \haibao\www\web\view\utility\Feature as FeatureUtility;
use haibao\www\data\ZtSpecial as ZtSpecialData;
use haibao\www\model\filter\ZtSpecial as ZtSpecialFilter;
use haibao\www\data\ZtSpecial;
use haibao\www\data\FeatureSerial;
use haibao\www\model\filter\FeatureDynamicDefine as FeatureDynamicDefineFilter;
use haibao\www\model\filter\FeatureParam as FeatureParamFilter;
use haibao\www\model\data\FeatureIni as FeatureIniModel;

class FeaturePublish extends \haibao\cms\business\Base{
	const FEATURE_CONTENT_TYPE_UPLOAD = 1;
	const FEATURE_CONTENT_TYPE_OTHER_FEATURE = 2;
	
	public static function addFeatureRecord($itemModels,$featureId,$defineId){
		if (!$featureId){
			throw new BusinessException('专题id不能为空');
		}
		$data = new FeaturePublishData();
		
		return $data->addFeatureRecord($itemModels,$featureId,$defineId);
	}
	
	public static function updateFeatureIni($featureId,$id,$arrSet){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		if (!$featureId){
			throw new BusinessException('专题id不能为空');
		}
		
		$data = new FeaturePublishData();
		$data->updateFeatureIni($featureId,$id, $arrSet);
		
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT,array_merge($arrSet,array('featureId'=>$featureId)));
	}
	
	public static function updateFeatureParamValue($id,$arrSet,$featureId){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		
		$data = new FeaturePublishData();
		$data->updateFeatureParamById($id, $arrSet,$featureId);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT,array_merge($arrSet,array('paramId'=>$id)));
	}
	
	public static function getAllDynamicItems($filter){
		$data = new FeaturePublishData();
		
		return $data->getAll($filter);
	}
	
	public static function delDynamicDefine($defineId){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		if (!$defineId){
			throw new BusinessException('动态数据定义id不能为空');
		}
		
		$data = new FeaturePublishData();
		$data->delDynamicDefine($defineId);
	
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, array('delDynamicDefine'=>$defineId));
	}
	
	public static function addDynamicDefine($model){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		
		$filter = new FeatureDynamicDefineFilter();
		$filter->where(FeatureDynamicDefineFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,$model->FeatureId);
		$filter->where(FeatureDynamicDefineFilter::CONDITION_FIELD_NAME_CODE,Condition::CONDITION_EQUAL,$model->Code);
		if (self::getAllDynamicDefineList($filter)){
			throw new BusinessException('动态数据名称已存在');
		}
		
		$data = new FeaturePublishData();
		$model->CreateTime = new \DateTime();
		$model->CreateBy = self::getCurrentUser()->Id;
		$data->addDynamicDefine($model);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, $model);
	}
	
	public static function updateDynamicDefine($model){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		if (!$model){
			throw new BusinessException('动态数据实体不能为空');
		}
		
		$filter = new FeatureDynamicDefineFilter();
		$filter->where(FeatureDynamicDefineFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,$model->FeatureId);
		$filter->where(FeatureDynamicDefineFilter::CONDITION_FIELD_NAME_CODE,Condition::CONDITION_EQUAL,$model->Code);
		$filter->where(FeatureDynamicDefineFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_NOTEQUAL,$model->Id);
		if (self::getAllDynamicDefineList($filter)){
			throw new BusinessException('动态数据名称已存在');
		}
		
		$data = new FeaturePublishData();
		$data->updateDynamicDefine($model);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, $model);
	}
	
	public static function delParamById($paramId){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		if (!$paramId){
			throw new BusinessException('参数id不能为空');
		}
		
		$data = new FeaturePublishData();
		$data->delParamById($paramId);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, array('delFeatureParam'=>$paramId));
	}
	
	public static function updateFeatureParam($id,$arrSet){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		if (!$id){
			throw new BusinessException('参数id不能为空');
		}
		
		$filter = new FeatureParamFilter();
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,$arrSet[FeatureParamFilter::CONDITION_FIELD_NAME_FEATURE_ID]);
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_CODE,Condition::CONDITION_EQUAL,$arrSet[FeatureParamFilter::CONDITION_FIELD_NAME_CODE]);
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_PARAM_TYPE,Condition::CONDITION_EQUAL,$arrSet[FeatureParamFilter::CONDITION_FIELD_NAME_PARAM_TYPE]);
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_NOTEQUAL,$id);
		
		if (self::getAllParamList($filter)){
			throw new BusinessException('参数名称已存在');
		}
		
		$data = new FeaturePublishData();
		$data->updateFeatureParam($id,$arrSet);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, array(array_merge($arrSet,array('id'=>$id))));
	}
	
	public static function addFeatureParam($model){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		
		$filter = new FeatureParamFilter();
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,$model->FeatureId);
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_CODE,Condition::CONDITION_EQUAL,$model->Code);
		$filter->where(FeatureParamFilter::CONDITION_FIELD_NAME_PARAM_TYPE,Condition::CONDITION_EQUAL,$model->ParamType);
		if (self::getAllParamList($filter)){
			throw new BusinessException('参数名称已存在');
		}
		
		$model->CreateTime = new \DateTime();
		$model->CreateBy = self::getCurrentUser()->Id;
		$data = new FeaturePublishData();
		$data->add($model);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, $model);
	}
	
	public static function addFeatureIni($model){
		self::checkOperation(self::FUNC_CODE_FEATURE_PARAM_MANAGER);
		if (!$model->FeatureId){
			throw new BusinessException('专题id不能为空');
		}
		
		$data = new FeaturePublishData();
		
		$data->addFeatureIni($model);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PARAM_MANAGER, $model);
	}
	
	public static function getAllIni($filter){
		$data = new FeaturePublishData();
		
		return $data->getAll($filter);
	}
	
	public static function getAllDynamicDefineList($filter){
		$data = new FeaturePublishData();
		
		return $data->getAll($filter);
	}
	
	public static function getAllParamList($filter){
		$data = new FeaturePublishData();
		
		return $data->getAll($filter);
	}
	
	public static function listFeature($featureId,$isList){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		
		if (!$featureId){
			throw new BusinessException('专题Id不能为空');
		}
		
		if ($isList == FeaturePublishModel::IS_LIST_DISABLE){
			$isList = FeaturePublishModel::IS_LIST_ENABLE;
		}else{
			$isList = FeaturePublishModel::IS_LIST_DISABLE;
		}
		
		$data = new FeaturePublishData();
		$data->listFeature($featureId,$isList);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT, array('修改专题显示状态',array($featureId=>$isList)));
	}
	
	public static function getDynamicList($id,$parameters){
		$data = new FeaturePublishData();
		
		return $data->getDynamicList($id,$parameters);
	}
	
	public static function delDynamic($itemGroupId){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		$data = new FeaturePublishData();
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT, array('删除动态数据',$itemGroupId));
		
		return $data->delDynamic($itemGroupId);
	}
	
	public static function getAllDynamic($filter){
		$data = new FeaturePublishData();
		
		return $data->getAll($filter);
	}
	
	/**
	 * 添加专题动态数据
	 * @param unknown $defineModel
	 * @param unknown $itemModels
	 * @param unknown $itemDataModels
	 */
	public static function addFeatureDynamic($defineModel,$itemModels,$itemDatas,$showTime){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		$data = new FeaturePublishData();
		
		//补全define
		$defineFilter = new \haibao\cms\model\filter\FeatureGroupDefine();
		$defineFilter->where(
				\haibao\cms\model\filter\FeatureGroupDefine::CONDITION_FIELD_NAME_GROUP_CODE,
				Condition::CONDITION_EQUAL,
				$defineModel->GroupCode
		);
		$defineFilter->where(
				\haibao\cms\model\filter\FeatureGroupDefine::CONDITION_FIELD_NAME_FEATURE_ID,
				Condition::CONDITION_EQUAL,
				$defineModel->FeatureId
		);
		if (!($result = $data->getOne($defineFilter)) ){
			$data->add($defineModel);
		}
		else{
			$defineModel = $result;
		}
		
		//补全item
		$itemCodes = array();
		foreach ($itemModels as $itemModel){
			array_push($itemCodes,$itemModel->ItemCode);
		}
		$itemFilter = new \haibao\cms\model\filter\FeatureGroupDefineItem();
		$itemFilter->where(
				\haibao\cms\model\filter\FeatureGroupDefineItem::CONDITION_FIELD_NAME_ITEM_CODE,
				Condition::CONDITION_IN,
				$itemCodes
		);
		$itemFilter->where(
				\haibao\cms\model\filter\FeatureGroupDefineItem::CONDITION_FIELD_NAME_GROUP_DEFINE_ID,
				Condition::CONDITION_EQUAL,
				$defineModel->Id
		);
		if ($items = $data->getAll($itemFilter)){
			foreach ($itemModels as $key=>$itemModel){
				$exist = false;
				foreach ($items as $item){
					if ($item->ItemCode == $itemModel->ItemCode){
						$exist = true;
					}
				}
		
				if ($exist){
					unset($itemModels[$key]);
				}
			}
		}
		if ($itemModels){
			foreach ($itemModels as $itemModel){
				$itemModel->GroupDefineId = $defineModel->Id;
			}
			$data->addAll($itemModels);
		}
		//重新获取itemModels的id
		$itemModels = $data->getAll($itemFilter);
		
		//添加item，group对应关系
		$itemGroupModel = new \haibao\cms\model\data\FeatureItemGroupData();
		$itemGroupModel->GroupDefineId = $defineModel->Id;
		$itemGroupModel->CreateTime = new \DateTime();
		$itemGroupModel->CreateBy = self::getCurrentUser()->Id;
		$itemGroupModel->ShowTime = $showTime;
		if (!$showTime){
			$itemGroupModel->ShowTime = $itemGroupModel->CreateTime;
		}
		$data->add($itemGroupModel);
		//添加itemdata
		$itemDataModels = array();
		foreach ($itemDatas as $key=>$value){
			$itemId = null;
			foreach ($itemModels as $itemModel){
				if ($value['code'] == $itemModel->ItemCode){
					$itemId = $itemModel->Id;
				}
			}
				
			$itemDataModel = new \haibao\cms\model\data\FeatureGroupDefineItemData();
			$itemDataModel->GroupDefineItemId = $itemId;
			$itemDataModel->ItemGroupDataId = $itemGroupModel->Id;
			$itemDataModel->ItemValue = $value['value'];
			array_push($itemDataModels,$itemDataModel);
		}
		
		$data->addAll($itemDataModels);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT, $itemDataModels);
	}
	
	/**
	 * 更新动态数据
	 */
	public static function updateFeatureDynamic($itemDataModels,$itemGroupId,$showTime){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		
		$data = new FeaturePublishData();
		$data->updateFeatureDynamic($itemDataModels,$itemGroupId,$showTime);
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT, $itemDataModels);
	}
	
	public static function getFeatureById($id){
		$models = self::getFeatureByIds(array($id));
		
		return array_pop($models);
	}
	
	public static function getFeatureByIds($ids){
		$filter = new FeaturePublishFilter();
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_IN,$ids);
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
		
		return self::searchFeature($filter);
	}
	
	public static function searchFeatureVote($filter){
		$data = new FeaturePublishData();
	
		return $data->getAll($filter);
	}
	
	public static function vote($id,$name){
		$data = new FeaturePublishData();
		
		return $data->vote($id,$name);
	}
	
	public static function publish($id,$url,$isH5,$listTime){
		self::checkOperation(self::FUNC_CODE_FEATURE_PUBLISH);
		if (!$id){
			throw new BusinessException('专题id不能为空',self::DATA_EMPTY_FEATURE_ID);	
		}
		if (!$url){
			throw new BusinessException('专题url不能为空');
		}
		$url = FeatureUtility::getFeatureUrl($url, $isH5);
		self::checkUrl($url,$id);
		
		//保存记录到原cms
		$filter = new FeaturePublishFilter();
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_EQUAL,$id);
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
		if ($models = self::searchFeature($filter)){
			$model = array_pop($models);
			$model->Url = $url;
			$model->PublishTime = new \DateTime();
			$model->PublishBy = self::getCurrentUser()->Id;
			$model->Status = FeaturePublishModel::STATUS_PUBLISH;
			$model->UpdateBy = self::getCurrentUser()->Id;
			$model->UpdateTime = new \DateTime();
			$model->IsH5 = $isH5;
			$model->ListTime = $listTime;
			
			$featureData = new FeaturePublishData();
			$arrSet = array(
					FeaturePublishFilter::CONDITION_FIELD_NAME_URL=>$model->Url,
					FeaturePublishFilter::CONDITION_FIELD_NAME_LIST_TIME=>$model->ListTime,
					FeaturePublishFilter::CONDITION_FIELD_NAME_PUBLISH_TIME=>$model->PublishTime,
					FeaturePublishFilter::CONDITION_FIELD_NAME_PUBLISH_BY=>$model->PublishBy,
					FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS=>$model->Status,
					FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_BY=>$model->UpdateBy,
					FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_TIME=>$model->UpdateTime,
					FeaturePublishFilter::CONDITION_FIELD_NAME_IS_H5=>$model->IsH5,
					FeaturePublishFilter::CONDITION_FIELD_NAME_LIST_TIME=>$model->ListTime
			);
			$featureData->updateById($id, $arrSet);
			
			if ($model->FeatureDefine->SerialId){
				$data = new \haibao\cms\data\FeatureSerial();
				$data->editSerial($model->FeatureDefine->SerialId, array(
						\haibao\cms\model\filter\FeatureSerial::CONDITION_FIELD_NAME_LAST_PUBLISH_TIME=>new \DateTime()
				));
			}
			
			if ($oldFeatureId = $featureData->getDataMigration($model, $model->Id)){
				//更新
				$ztSpecialData = new ZtSpecialData();
				$oldFeature = $ztSpecialData->getOneById($oldFeatureId);
				$featureData->updateOldFeatureRecord($model,$oldFeature);
			}
			else{
				//第一次发布
				$oldFeatureId = $featureData->saveOldFeatureRecord($model);
				$featureData->addDataMigrationMap($model, $oldFeatureId);
			}
			
			//编译专题并上传
			//保存压缩包至mongo
			self::updateFeatureZip(null,$model);
			$combinePath = FeatureUtility::combineFeature($model,$oldFeatureId);
			if ($combinePath){
				FeatureUtility::uploadFeature($model->Url, $combinePath,$model->IsH5);
			}
		}
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_PUBLISH, array($id));
	}
	
	public static function getVideoCates($filter){
		$data = new FeaturePublishData();
		
		return $data->getVideoCates($filter);
	}
	
	public static function getFeatureImgPath($features){
		$result = array();

		if ($features){
			$ids = array();
			foreach ($features as $feature){
				if ($feature->PictureId && $feature->PictureId){
					$imgPath = FeatureUtility::getFeatureTmpPath().'/'.md5($feature->PictureId).'/'.FileUtility::getMd5FileName($feature->PictureName);
					if (!file_exists($imgPath)){
						array_push($ids,$feature->PictureId);
					}else{
						$viewUrl = '/'.FeatureUtility::FEATURE_BASE_URL.'/'.FeatureUtility::FEATURE_TMP_PATH.'/'.md5($feature->PictureId).'/'.FileUtility::getMd5FileName($feature->PictureName);
						$result[$feature->PictureId] = $viewUrl;
					}
				}	
			}
			
			if ($ids){
				$data = new FeaturePublishData();
				$files = $data->getFeatureImgByIds($ids);
				if ($files){
					foreach ($files as $file){
						$id = strval($file->file['_id']);
						$fileName = $file->file['fileName'];
						$imgPath = FeatureUtility::getFeatureTmpPath().'/'.md5($id).'/'.FileUtility::getMd5FileName($fileName);
						FileUtility::filePutContents($imgPath,$file->getBytes());
						$viewUrl = '/'.FeatureUtility::FEATURE_BASE_URL.'/'.FeatureUtility::FEATURE_TMP_PATH.'/'.md5($id).'/'.FileUtility::getMd5FileName($fileName);
						$result[$id] = $viewUrl;
					}
				}
			}
		}
		
		return $result;
	}
	
	/**
	 * 重新上传Feature压缩包并解压
	 * @param string $tmpName
	 * @param string $fileName
	 * @param string $toPath
	 */
	/* public static function reUploadFeatureZip($file,$toPath){
		$path = self::uploadFile($file);
		if ($path){
			$path = FeatureUtility::getFeatureFilePath().$path;	
			if (!FeatureUtility::checkMainFileNameFromZip($path)){
				throw new BusinessException('缺少主文件');
			}
				
			$zip = new \ZipArchive();
			$zip->open($path);
			if (file_exists($toPath)){
				FileUtility::removeResource($toPath,false);
			}
			$zip->extractTo($toPath);
			$zip->close();
		}
	} */
	
	public static function reuploadfeatureSvnUrl($svnUrl,$trueToPath,$featureName){
		$dir = FeatureUtility::getFeatureTmpPath().'/'.date('YmdHis').mt_rand(100,900).'/'.md5($featureName);
		FileUtility::makeNewDir($dir);
		if(!SvnUtility::checkout(FeatureUtility::getFullSvnUrl($svnUrl), $dir))
		{
			throw new BusinessException('从svn获取专题失败');
		}
		$dir = $dir.'/'.baseName($svnUrl);
		if (!FeatureUtility::checkMainFileNameFromDir($dir)){
			throw new BusinessException('缺少主文件');
		}
		FileUtility::copyResource($dir, $trueToPath);
	}
	
	public static function updateFeatureZip($id,$model = null){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		
		if (!$model){
			$model = self::getFeatureById($id);	
		}
		
		if ($model){
			$fileId = $model->FileId;
			$zipName = md5($model->FeatureName).'.zip';
			$truePath = FeatureUtility::getFeatureFilePath().'/'.md5($model->FeatureName);
			$zipPath = FeatureUtility::getFeatureTmpPath().'/'.FileUtility::getMd5FileName($zipName);
			FileUtility::zipDir($truePath, $zipPath);
			$content = file_get_contents($zipPath);
			
			$data = new FeaturePublishData();
			$newFileId = $data->storeFeatureZip($content,array('fileName'=>$zipName));
			$data->updateById($model->Id, array(
				FeaturePublishFilter::CONDITION_FIELD_NAME_FILE_ID=>$newFileId,
				FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_BY =>self::getCurrentUser()->Id,
				FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_TIME=>new \DateTime()
			));
			$data->delFeatureZipById($fileId);
		}
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT, array('FileId'=>$newFileId,'','Id'=>$model->Id));
	}
	
	public static function getFeatureZipById($id){
		$data = new FeaturePublishData();

		return $data->getFeatureZipById($id);
	}
	
	public static function delFeature($id){
		self::checkOperation(self::FUNC_CODE_FEATURE_DEL);
		if (!$id){
			throw new BusinessException('专题Id不能为空',self::DATA_EMPTY_FEATURE_ID);
		}
		
		$data = new FeaturePublishData();
		$filter = new FeaturePublishFilter();
		$filter->select(array(
			FeaturePublishFilter::CONDITION_FIELD_NAME_FILE_ID
		));
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_EQUAL,$id);
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
		$models = self::searchFeature($filter);
		
		if (!$models){
			throw new BusinessException('未找到专题');
		}
		
		$model = array_pop($models);
		try{
			$data->beginTranscation();
			$arrSet = array(
				\haibao\cms\model\filter\FeaturePublish::CONDITION_FIELD_NAME_STATUS=>\haibao\cms\model\data\FeaturePublish::STATUS_DISABLE
			);
			$data->updateById($id, $arrSet);
			/*
			 * 暂时不删附件 
			$data->delFeatureZipById($model->FileId);
			if ($model->PictureId){
				$data->delFeatureImgById($model->PictureId);
			} */
			$data->endTranscation();
		}
		catch (\Exception $e){
			$data->rollback();
			throw $e;	
		}

		self::saveOperateHistory(self::FUNC_CODE_FEATURE_DEL, $id);
	}
	
	/**
	 * 修改专题
	 * @param int $id
	 * @param array $arrSet
	 */
	public static function updateFeature($id,$arrSet,$imgPath,$pictureId){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		if (!$id){
			throw new BusinessException('专题id不能为空',self::DATA_EMPTY_FEATURE_ID);
		}
		if (isset($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_FEATURE_NAME])){
			$featureName = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_FEATURE_NAME];
			
			if (!$featureName){
				throw new BusinessException('专题名称不能为空',self::DATA_EMPTY_FEATURE_NAME);
			}
			
			$filter = new FeaturePublishFilter();
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_FEATURE_NAME,Condition::CONDITION_EQUAL,$featureName);
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_NOTEQUAL,$id);
			if (self::searchFeature($filter)){
				throw new BusinessException('专题名称已存在',self::DATA_ERROR_FEATURE_NAME_EXIST);
			}	
		}
		
		if (!empty($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_URL])){
			self::checkUrl($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_URL],$id);
		}
		
		$arrSet = array_merge($arrSet,array(
			FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_BY=>self::getCurrentUser()->Id,
			FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_TIME=>new \DateTime()
		));
		
		$model = self::getFeatureById($id);		
		$data = new FeaturePublishData();
		
		try{
			$data->beginTranscation();
			$trueImgPath = '';
			if ($imgPath){
				$trueImgPath = FeatureUtility::getFeatureFilePath().$imgPath;
				$arr = array(
						'tmp_name'=>$trueImgPath,
						'name'=>$trueImgPath
				);
				$imgInfo = \haibao\cms\business\ImageLibrary::saveUpload($arr, \haibao\cms\model\data\ImageLibrary::UPLOAD_SOURCE_FEATURE,false);
				$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_PICTURE_ID] = $imgInfo['id'];
			}
			
			$data->updateFeature($id,$arrSet);
			
			//如果选择了所属系列及期号，更新serial表
			if (
					!empty($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_SERIAL_ID]) 
				&& 	!empty($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_ISSUE])
			){
				$serialData = new \haibao\cms\data\FeatureSerial();
				$serialData->updateById($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_SERIAL_ID], array(
						\haibao\cms\model\filter\FeatureSerial::CONDITION_FIELD_NAME_CURRENT_ISSUE=>$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_ISSUE]
				));
			}
			
			//如果专题已发布，同步信息到旧专题列表
			if ($model->Status == FeaturePublishModel::STATUS_PUBLISH){
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_TITLE] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_FEATURE_NAME];
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_DESCRIPTION] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_DESCRIPTION];
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_URL] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_URL];
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_TAG] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_CLASS_ID];
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_ZT_VIDEO_CATE] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_COLUMN_ID];
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_KEYWORDS] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_KEYWORDS];
				$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_DATE] = $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_LIST_TIME];
				
				if ($trueImgPath){
					$picName = FeatureUtility::saveOldFeatureImage($trueImgPath,file_get_contents($trueImgPath));
					$oldFeatureSet[ZtSpecialFilter::CONDITION_FIELD_NAME_PIC] = $picName;
				}
				
				$ztSpecialId = $data->getDataMigration($model, $model->Id);
				$ztSpecialData = new ZtSpecialData();
				$ztSpecialData->updateById($ztSpecialId, $oldFeatureSet);
				
				//如果url有改动，发布到新url
				if ($model->Url != $arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_URL]){
					$zipFile = $data->getFeatureZipById($model->FileId);
					FeatureUtility::extractFeatureZip($zipFile->file['fileName'],$zipFile->getBytes(),$featureName);
					$combinePath = FeatureUtility::combineFeature($model,$ztSpecialId);
					if ($combinePath){
						FeatureUtility::uploadFeature(
							$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_URL], 
							$combinePath,
							$model->IsH5
						);
					}
				}
			}
			
			//删除旧图片
			if ($imgPath && $pictureId){
				\haibao\cms\business\ImageLibrary::deleteImage($pictureId);
			}
			
			$data->endTranscation();
		}
		catch (\Exception $e){
			$data->rollBack();
			throw $e;
		}
		
		//删除本地图片缓存
		if ($imgPath && $pictureId){
			$imgDir = FeatureUtility::getFeatureTmpPath().'/'.md5($pictureId);
			FileUtility::removeResource($imgDir);
		}
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_EDIT, array_merge($arrSet,array('id'=>$id)));
	}
	
	/**
	 * 添加专题
	 * @param \haibao\cms\model\data\FeaturePublish $model
	 */
	public static function addFeature($model,$contentType,$otherFeatureId,$svnUrl,$imgPath = null){
		self::checkOperation(self::FUNC_CODE_FEATURE_ADD);
		if (!$model->FeatureName){
			throw new BusinessException('专题名称不能为空',self::DATA_EMPTY_FEATURE_NAME);
		}
		
		$filter = new FeaturePublishFilter();
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_FEATURE_NAME,Condition::CONDITION_EQUAL,$model->FeatureName);
		if (self::searchFeature($filter)){
			throw new BusinessException('专题名称已存在',self::DATA_ERROR_FEATURE_NAME_EXIST);
		}
		
		if ($model->Url){
			self::checkUrl($model->Url);
		}
		
		$filter = new FeaturePublishFilter();
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
		$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_FEATURE_NAME,Condition::CONDITION_EQUAL,$model->FeatureName);
		if (self::searchFeature($filter)){
			throw new BusinessException('专题名称已存在',self::DATA_ERROR_FEATURE_NAME_EXIST);
		}
		
		$data = new FeaturePublishData();
		$content = null;
		$fileName = '';
		if ($contentType == self::FEATURE_CONTENT_TYPE_UPLOAD){
			$filter = new FeaturePublishFilter();
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_SVN_ADDRESS,Condition::CONDITION_EQUAL,$svnUrl);
			if (self::searchFeature($filter)){
				throw new BusinessException('svn地址已被其他专题使用');
			}
			
			$model->SvnAddress = $svnUrl;
			
			//手动 svn
			$dir = FeatureUtility::getFeatureTmpPath().'/'.date('YmdHis').mt_rand(100,900).'/'.md5($model->FeatureName);
			FileUtility::makeNewDir($dir);
			if(!SvnUtility::checkout(FeatureUtility::getFullSvnUrl($svnUrl), $dir))
			{
				throw new BusinessException('从svn获取专题失败');
			}
			$zipFromPath = $dir.'/'.baseName($svnUrl);
			
			if (!FeatureUtility::checkMainFileNameFromDir($zipFromPath)){
				throw new BusinessException('缺少主文件');
			}
			$zipToPath = $dir.'.zip';
			FileUtility::zipDir($zipFromPath,$zipToPath);
			$fileName = md5($model->FeatureName).'.zip';
			$content = file_get_contents($zipToPath);
		}
		else if ($contentType == self::FEATURE_CONTENT_TYPE_OTHER_FEATURE){
			//其他专题
			$filter = new FeaturePublishFilter();
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL,$otherFeatureId);
			$filter->select(array(
				FeaturePublishFilter::CONDITION_FIELD_NAME_FILE_ID,
			));
			$features = self::searchFeature($filter);
			if ($features){
				$feature = array_pop($features);
				$file = $data->getFeatureZipById($feature->FileId);
				if ($file){
					$content = $file->getBytes();
					$fileName = $file->file['fileName'];
				}
			}
		}
		
		if (!$content){
			throw new BusinessException('专题内容不能为空',self::DATA_EMPTY_FEATURE_CONTENT);
		}
		
		//图片处理
		if ($imgPath){
			$trueImgPath = FeatureUtility::getFeatureFilePath().$imgPath;
			$arr = array(
					'tmp_name'=>$trueImgPath,
					'name'=>$trueImgPath
			);
			$imgInfo = \haibao\cms\business\ImageLibrary::saveUpload($arr, \haibao\cms\model\data\ImageLibrary::UPLOAD_SOURCE_FEATURE,false);
			$model->PictureId = $imgInfo['id'];
			$model->PictureName = $imgInfo['imageUrl'];
		}
		
		$userId = self::getCurrentUser()->Id;
		$time = new \DateTime();
		$iniModel = new FeatureIniModel(); 
		$model->UpdateBy = $userId;
		$model->UpdateTime = $time;
		$model->CreateBy = $userId;
		$model->CreateTime = $time;
		$model->Status = FeaturePublishModel::STATUS_NOT_PUBLISH;
		$iniModel->WeixinShare = FeatureIniModel::STATUS_DISABLE;
		$iniModel->Vote = FeatureIniModel::STATUS_DISABLE;
		$iniModel->Title = '';
		$iniModel->PcShare = FeatureIniModel::STATUS_DISABLE;
		$iniModel->Keywords = '';
		$iniModel->HaibaoHeader = FeatureIniModel::HEADER_DISABLE;
		$iniModel->HaibaoBottom = FeatureIniModel::STATUS_DISABLE;
		$iniModel->GoTop = FeatureIniModel::STATUS_DISABLE;
		$iniModel->Dynamic = FeatureIniModel::STATUS_DISABLE;
		$iniModel->Description = '';
		$iniModel->Record = FeatureIniModel::STATUS_DISABLE;
		
		$data = new FeaturePublishData();
		try{
			$data->beginTranscation();
			
			$model->FileId = $data->storeFeatureZip($content,array('fileName'=>$fileName));
			$data->addFeature($model);
			
			$iniModel->FeatureId = $model->Id;
			$data->add($iniModel);
			
			//如果选择了所属系列及期号，更新serial表
			if ($model->SerialId && $model->Issue){
				$serialData = new \haibao\cms\data\FeatureSerial();
				$serialData->updateById($model->SerialId, array(
						\haibao\cms\model\filter\FeatureSerial::CONDITION_FIELD_NAME_CURRENT_ISSUE=>$model->Issue
				));
			}
			
			$data->endTranscation();
		}
		catch(\Exception $e){
			$data->rollback();
			throw $e;
		}
		
		self::saveOperateHistory(self::FUNC_CODE_FEATURE_ADD, $model->toArray(true,true));
	}
	
	public static function setNewImg($indexPath,$dirPath,$newPath,$oldImgPath,$editName){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
		$newImgContent = '';
		$trueNewPath = FeatureUtility::getFeatureFilePath().$newPath;
		$content = file_get_contents($trueNewPath);
		if (stripos($oldImgPath,'http') === false){
			//本地图片
			$truePath = str_replace(FeatureUtility::FEATURE_BASE_URL,FeatureUtility::FEATURE_PATH,$oldImgPath);
			$truePath = \haibao\frame\Environment::path().$truePath;
			if (file_exists($truePath)){
				file_put_contents($truePath,$content);
			}
		}
		else{
			//网络图片
			//上传图片到本地文件夹，并修改src
			$newImgPath = FeatureUtility::FEATURE_IMG_DIR.'/'.basename($newPath);
			$newImgTruePath = FeatureUtility::getFeatureFilePath().'/'.$dirPath.'/'.$newImgPath;
			FileUtility::filePutContents($newImgTruePath,$content);
			
			//找到edit标签
			$mainFilePath = FeatureUtility::getFeatureFilePath().'/'.$dirPath.'/'.$indexPath;
			$mainFileHtml = file_get_contents($mainFilePath);
			$pattern = '<!--ed|'.$editName.'-->';
			$startPos = mb_stripos($mainFileHtml,$pattern,0,'utf-8');
			$endPos = mb_strripos($mainFileHtml,$pattern,0,'utf-8');
			
			if (false !== $startPos && false !== $endPos){
				//替换img标签的src
				$patternLength = mb_strlen($pattern,'utf-8');
				$editContent = mb_substr($mainFileHtml,$startPos+$patternLength,$endPos-$startPos-$patternLength,'utf-8');
				$imgPattern = '/src(.*?)=(.*?)(\'|")((.*?))(\'|")/is';
				$replace = 'src="'.$newImgPath.'"';
				$newImgContent = preg_replace($imgPattern,$replace,$editContent);
				$startLength = $startPos + mb_strlen($pattern,'utf-8');
				$endLength = mb_strlen($mainFileHtml,'utf-8') - $endPos;
				$newContent = mb_substr($mainFileHtml,0,$startLength,'utf-8').$newImgContent.mb_substr($mainFileHtml,$endPos,$endLength,'utf-8');
				file_put_contents($mainFilePath,$newContent);
			}
		}
		
		return $newImgContent;
	}
	
	public static function clearDir($dir){
		FileUtility::removeResource($dir,false);
	}
	
	/**
	 * 上传
	 */
	public static function uploadFile($file){
		$imgInfo = null;
		if (FileUtility::getFileType($file['name']) == FileUtility::FILE_TYPE_IMG){
			if (!FileUtility::checkImgSize($file,$imgInfo)){
				throw new BusinessException('图片大小不符');
			}
		}
		$tmpName = $file['tmp_name'];
		$fileName = $file['name'];
		//判断上传权限？
		$path = '/'.FeatureUtility::FEATURE_TMP_PATH.'/'.date('YmdHis').mt_rand(100,900).'/'.FileUtility::getMd5FileName($fileName);
		$trueFilePath = FeatureUtility::getFeatureFilePath().$path;
		FileUtility::filePutContents($trueFilePath);		
		move_uploaded_file($tmpName, $trueFilePath);
		
		return array('path'=>$path,'imgInfo'=>$imgInfo);
	}
	
	/**
	 * 专题搜索
	 * @param \haibao\cms\model\filter\FeaturPublish $filter
	 */
	public static function searchFeature($filter){
		$data = new FeaturePublishData();
		
		return $data->getAll($filter);
	}
	
	public static function checkUrl($url,$id = null){
		if ($url){
			$filter = new FeaturePublishFilter();
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_URL,Condition::CONDITION_EQUAL,$url);
			$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_NOTEQUAL,FeaturePublishModel::STATUS_DISABLE);
			if ($id){
				$filter->where(FeaturePublishFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_NOTEQUAL,$id);
			}
			
			if (self::searchFeature($filter)){
				throw new BusinessException('url已存在',self::DATA_ERROR_FEATURE_URL_EXIST);
			}
			
			if (stripos($url,FeatureUtility::FEATURE_UPLOAD_BASE_URL) === false && stripos($url,FeatureUtility::FEATURE_UPLOAD_BASE_URL_H5) === false){
				throw new BusinessException('url格式不正确');
			}
		}
	}
	
	public static function setFileContent($path,$content,$newPath = null){
		self::checkOperation(self::FUNC_CODE_FEATURE_EDIT);
	
		if ($newPath){
			$trueNewPath = FeatureUtility::getFeatureFilePath().'/'.$newPath;
			$content = file_get_contents($trueNewPath);
		}
	
		$truePath = FeatureUtility::getFeatureFilePath().'/'.$path;
		if (file_exists($truePath) && $content){
			file_put_contents($truePath,$content);
		}
	}

	public static function uploadImage($file, $coorData){
        $basePath = \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\cms\Config::IMAGE_UPLOAD_BASE_PATH).'/'.date('Y').DIRECTORY_SEPARATOR.date('md').DIRECTORY_SEPARATOR.microtime(true);
        $extension = pathinfo($file['name']);
        $basePath .= '.' . strtolower(isset($extension['extension']) ? $extension['extension'] : 'jpg');
        $savePath = \haibao\frame\Environment::path() . str_replace(array('/', '\\'), '/', $basePath);

        $path = pathinfo( $savePath );
        if (!is_dir($path['dirname'])){
            mkdir($path['dirname'], 750, true);
        }
        file_put_contents($savePath, file_get_contents($file['tmp_name']));

        $sourceInfo = getimagesize($savePath);
//        $OrgWidth = $sourceInfo[0];
//        $OrgHeight = $sourceInfo[1];
        $OrgMime = $sourceInfo['mime'];


        switch ($OrgMime) {
            case 'image/gif':
                $sourceImage = imagecreatefromgif($savePath);
                break;
            case 'image/jpeg':
                $sourceImage = imagecreatefromjpeg($savePath);


                $exif = exif_read_data($savePath);
                if($exif && isset($exif['Orientation'])){
                    if($exif['Orientation'] == 3) {
                        $sourceImage = imagerotate($sourceImage, 180, 0);
                        imagejpeg($sourceImage, $savePath, 100);
                    } elseif($exif['Orientation'] == 6) {
                        $sourceImage = imagerotate($sourceImage, -90, 0);
                        imagejpeg($sourceImage, $savePath, 100);
                    } elseif($exif['Orientation'] == 8) {
                        $sourceImage = imagerotate($sourceImage, 90, 0);
                        imagejpeg($sourceImage, $savePath, 100);
                    }
                }
                break;
            case 'image/png':
                $sourceImage = imagecreatefrompng($savePath);
                break;
            default:
                return false;
                break;
        }

        $coor = json_decode($coorData);
        $targetImage = imagecreatetruecolor($coor->width, $coor->height);
        imagecopyresampled($targetImage, $sourceImage, 0, 0, $coor->x, $coor->y, $coor->width, $coor->height, $coor->width, $coor->height);


        $image = imagecreatefromjpeg($savePath);


       switch ($OrgMime) {
            case 'image/gif':
                imagegif($targetImage, $savePath);
                break;
            case 'image/jpeg':
                imagejpeg($targetImage, $savePath);
                break;
            case 'image/png':
                imagepng($targetImage, $savePath);
                break;
        }
        imagedestroy($targetImage);

        imagedestroy($sourceImage);
        return \haibao\cms\business\control\Base::getImageLink($basePath,700 ,700, 90, 0);

    }
}	